// 二次封装axios
import axios from 'axios'
import Vue from 'vue'
import qs from 'qs'
import { Toast } from 'vant'
import { gettoken } from './index'
import router from '@/router'

const vm = new Vue()

const request = axios.create({
  baseURL: process.env.BASE_URL === 'development' ? '/conner' : 'https://api.it120.cc/conner',
  timeout: 8000
})
// 请求拦截
request.interceptors.request.use(function (config) {
  if (gettoken()) {
    config.headers.token = gettoken()
  }
  if (config.method === 'post') {
    config.data = qs.stringify(config.data)
  }
  vm.$showLoading()
  return config
}, function (error) {
  vm.$hideLoading()
  return Promise.reject(error)
})
// 响应拦截
request.interceptors.response.use(response => {
  // 登录过期
  if (response.data.code === 2000) {
    Toast.fail({
      success: response.data.msg,
      duration: 1500,
      onClose: () => {
        router.push('/login')
        localStorage.removeItem('name')
        localStorage.removeItem('uid')
      }
    })
  }
  vm.$hideLoading()
  return response
}, error => {
  vm.$hideLoading()
  return Promise.resolve(error.response)
})

export default request
